
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:test_flutter/common/net/address.dart';
import 'package:test_flutter/common/style/common_style.dart';
import 'package:test_flutter/page/home_page.dart';

/// 登录页面
class LoginPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _LoginPage();
  }
}

class _LoginPage extends State<LoginPage> with LoginBLoC {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => {
        FocusScope.of(context).requestFocus(FocusNode())
      },
      child: Scaffold(
        body: Container(
          color: Theme.of(context).primaryColor,
          child: Center(
            child: SafeArea(
              child: SingleChildScrollView(
                child: Card(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  color: UIColors.common_color_white,
                  elevation: 5.0,
                  margin: EdgeInsets.only(left: 30, right: 30),
                  child: Padding(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      children: <Widget>[
                        /// logo
                        Container(
                          width: 80,
                          height: 80,
                          margin: EdgeInsets.only(bottom: 20),
                          child:
                          Image.asset("static/images/ic_logo.png"),
                        ),
                        /// 用户名
                        Row(
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(right: 6),
                              child: Icon(Icons.person,
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: TextField(
                                decoration: InputDecoration(
                                  hintText: 'github用户名，请不要用邮箱',
                                  enabledBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(color: UIColors.common_color_white1, width: 1)
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(color: UIColors.common_color_black1, width: 2)
                                  ),
                                ),
                                onChanged: (v) => {
                                  _username = v
                                },
                                controller: userController,
                              ),
                            )
                          ],
                        ),
                        /// 密码
                        Container(
                          margin: EdgeInsets.only(top: 10),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(right: 6),
                                child: Icon(Icons.keyboard,
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: TextField(
                                  keyboardType: TextInputType.visiblePassword, /// 设置输入类型
                                  decoration: InputDecoration(
                                    hintText: '请输入密码',
                                    enabledBorder: UnderlineInputBorder( /// 默认的边框背景
                                        borderSide: BorderSide(color: UIColors.common_color_white1, width: 1)
                                    ),
                                    focusedBorder: UnderlineInputBorder(/// 获取焦点的边框背景
                                        borderSide: BorderSide(color: UIColors.common_color_black1, width: 2)
                                    ),
                                  ),
                                  onChanged: (v) => {
                                    _password = v
                                  },
                                  controller: pwdController, /// TextEditingController：获取输入框数据
                                ),
                              )
                            ],
                          ),
                        ),
                        /// 登录按钮
                        Row(
                          children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Container(
                                margin: EdgeInsets.only(right: 5, top: 16),
                                child: TextButton(
                                  child: Text('账号登录', style: TextStyle(color: UIColors.common_color_white),),
                                  // color: UIColors.common_color_black, // 默认颜色
                                  // highlightColor: UIColors.common_color_black1, // 按下的颜色
                                  // splashColor: UIColors.common_color_white1, // 水波纹颜色
                                  // shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2))),
                                  onPressed: () => {
                                    print("账号登录"),
                                    loginIn()
                                  },
                                ),),
                            ),

                            Expanded(
                              flex: 1,
                              child: Container(
                                margin: EdgeInsets.only(left: 5, top: 16),
                                child: TextButton(
                                  child: Text('安全登录', style: TextStyle(color: UIColors.common_color_white),),
                                  style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.all(UIColors.common_color_black),
                                    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2)))),
                                  ),
                                  onPressed: () => {
                                    print("安全登录")
                                  },
                                ),),
                            )
                          ],
                        ),
                        /// 切换语音
                        Container(
                          margin: EdgeInsets.only(top: 20),
                          child: TextButton(
                            child: Text("切换语言", style: TextStyle(color: UIColors.common_color_black2)),
                            onPressed: () => {
                              print("切换语言")
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
        // resizeToAvoidBottomPadding: false,
      ),
    );
  }

}

mixin LoginBLoC on State<LoginPage> {

  final TextEditingController userController = new TextEditingController();
  final TextEditingController pwdController = new TextEditingController();
  var _username = "";
  var _password = "";

  loginIn() {
    if(_username.isEmpty){
      return;
    }
    if(_password.isEmpty) {
      return;
    }
    print("username: $_username password: $_password");
    oauthLoginIn(_username, _password);
  }

  void oauthLoginIn(String username, String password) async{
    Map<String, dynamic> params = {
      "client_id": "Iv1.bdf39a1b452c20e1",
      "client_secret": "614eb6a79505096e4f9730dacca9f25fc6390356",
    };
    try{
      BaseOptions options = new BaseOptions(
        method: "get",
        baseUrl: Address.HOST,
        connectTimeout: 12000,
        sendTimeout: 12000,
        receiveTimeout: 12000,
      );
      Dio dio = new Dio(options);
      dio.interceptors.add(LogInterceptor());
      var response = await dio.get("users/$username");
      var json = jsonDecode("$response");
      var userEntity = UserEntity.fromJson(json);
      print("response:$userEntity");
      /// 登录成功，跳转主页面
      Navigator.of(context).pop();
      Navigator.of(context).push(MaterialPageRoute(builder: (context) => HomePage()));
    }catch(e){
      print("error:$e");
    }
  }

  @override
  void initState() {
    super.initState();
    _username = "";
    _password = "";
    userController.addListener(userControllerChange);
    pwdController.addListener(pwdControllerChange);
  }

  userControllerChange() {
    _username = userController.text;
  }

  pwdControllerChange() {
    _password = pwdController.text;
  }

  @override
  void dispose() {
    super.dispose();
    userController.removeListener(userControllerChange);
    pwdController.removeListener(pwdControllerChange);
  }
}

class UserEntity{
  int id = 0;
  String login = "";
  String avatar_url = "";

  UserEntity();

  UserEntity.fromJson(Map<String, dynamic> json)
      : id = json['id'], login = json['login'], avatar_url = json['avatar_url'];

  Map<String, dynamic> toJson() => {
    'id': id,
    'login': login,
    'avatar_url': avatar_url,
  };

  @override
  String toString() {
    return 'UserEntity{id: $id, login: $login, avatar_url: $avatar_url}';
  }
}
